using System.Net.Http;
using System.Text;
using System.Text.Json;
using Xunit;
using Xunit.Abstractions;
using FluentAssertions;
using SG3L_RAG.Application.DTOs;
using SG3L_RAG.Application.DTOs.Auth;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Testing;
using SG3L_RAG.Api;

namespace SG3L_RAG.ApiTests
{
    public class ApiTestBase : IClassFixture<WebApplicationFactory<Program>>
    {
        protected readonly HttpClient _client;
        protected readonly ITestOutputHelper _output;
        protected string? _authToken = null;

        public ApiTestBase(WebApplicationFactory<Program> factory, ITestOutputHelper output)
        {
            _client = factory.CreateClient();
            _output = output;
            
            // 获取测试token
            var loginRequest = new SG3L_RAG.Application.DTOs.Auth.LoginDto
            {
                Username = "syl1",
                Password = "123456"
            };
            
            var loginResponse = _client.PostAsync("/api/auth/login", 
                new StringContent(JsonSerializer.Serialize(loginRequest), Encoding.UTF8, "application/json")).ConfigureAwait(false).GetAwaiter().GetResult();
            
            if (loginResponse.IsSuccessStatusCode)
            {
                var content = loginResponse.Content.ReadAsStringAsync().Result;
                var authResult = JsonSerializer.Deserialize<AuthResponseDto>(content);
                _authToken = authResult?.Token;
                
                if (!string.IsNullOrEmpty(_authToken))
                {
                    _client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_authToken}");
                }
            }
        }
    }

    public class AuthControllerTests : ApiTestBase
    {
        public AuthControllerTests(WebApplicationFactory<Program> factory, ITestOutputHelper output) 
            : base(factory, output) { }

        [Fact]
        public async Task Login_WithValidCredentials_ShouldReturnToken()
        {
            // Arrange
            var request = new SG3L_RAG.Application.DTOs.Auth.LoginDto
            {
                Username = "syl1",
                Password = "123456"
            };

            // Act
            var response = await _client.PostAsync("/api/auth/login", 
                new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json")).ConfigureAwait(false);

            // Assert
            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsStringAsync();
            content.Should().NotBeNullOrEmpty();
        }
    }

    public class ChatControllerTests : ApiTestBase
    {
        public ChatControllerTests(WebApplicationFactory<Program> factory, ITestOutputHelper output) 
            : base(factory, output) { }

        [Fact]
        public async Task SendMessage_WithValidRequest_ShouldReturnResponse()
        {
            // Arrange
            var request = new ChatRequestDto
            {
                Question = "What is RAG?",
                ConversationId = Guid.NewGuid(),
                UserId = Guid.Parse("550e8400-e29b-41d4-a716-446655440000"), // 使用测试用户ID
                UseRAG = true,
                MaxResults = 5,
                SimilarityThreshold = 0.7f
            };

            // Act
            var response = await _client.PostAsync("/api/chat/ask", 
                new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json"));

            // Assert
            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsStringAsync();
            content.Should().NotBeNullOrEmpty();
        }
    }

    public class VectorSearchControllerTests : ApiTestBase
    {
        public VectorSearchControllerTests(WebApplicationFactory<Program> factory, ITestOutputHelper output) 
            : base(factory, output) { }

        [Fact]
        public async Task Search_WithValidQuery_ShouldReturnResults()
        {
            // Arrange
            var request = new VectorSearchRequestDto
            {
                Query = "What is RAG?",
                TopK = 5,
                Threshold = 0.5f
            };

            // Act
            var response = await _client.PostAsync("/api/search/chunks", 
                new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json"));

            // Assert
            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsStringAsync();
            content.Should().NotBeNullOrEmpty();
        }
    }
}
